package com.changgou.user.config;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.stream.Collectors;

@Configuration
@EnableResourceServer
//开启方法上的PreAuthorize
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class UserResourceServerConfig extends ResourceServerConfigurerAdapter {

     public static final String PUBLIC_KEY="public.key";
     @Bean
    public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter){
         return new JwtTokenStore(jwtAccessTokenConverter);
     }
     @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
         JwtAccessTokenConverter converter=new JwtAccessTokenConverter();
         converter.setVerifierKey(getPublicKey());
         return converter;
     }
     public  String getPublicKey(){
         ClassPathResource classPathResource = new ClassPathResource(PUBLIC_KEY);
         try {
             InputStreamReader inputStreamReader = new InputStreamReader(classPathResource.getInputStream());
             BufferedReader br = new BufferedReader(inputStreamReader);
            return br.lines().collect(Collectors.joining("\n"));

         } catch (IOException e) {
             e.printStackTrace();
             return null;
         }

     }
     @Override
     public void configure(HttpSecurity http) throws Exception {
         http.authorizeRequests()
                 .antMatchers("/user/add","/user/load/**")
                 .permitAll()
                 .anyRequest()
                 .authenticated();

     }
}
